package com.ytk.icerain.api.dao;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import com.xunjia.exception.XunjiaException;
import com.xunjia.json.JSONArray;
import com.xunjia.json.JSONException;
import com.xunjia.json.JSONObject;
import com.yam.michael.hibernate.pojo.Keywords;
import com.yam.michael.hibernate.pojo.KeywordsAdvInfo;
import com.yam.michael.service.IUserService;
import com.ytk.icerain.Config;

public class KeyswordsDao {
	public String getKeywords(String keywords,int size,String type) {		
		ApplicationContext context = new FileSystemXmlApplicationContext(Config.BASE_URL+"WEB-INF/applicationContext.xml");
		IUserService api = null;
		try {
			api = (IUserService) context.getBean("userService");
		} catch (BeansException e) {
			e.printStackTrace();
		}
		List<Keywords> list = null;
		try {
			list = api.getKeywordsAdvByKeywordsLike(keywords,size,type);
		} catch (XunjiaException e) {
			e.printStackTrace();
		}
		JSONArray jArr = new JSONArray();
		Document document = DocumentHelper.createDocument();
	    Element adList = document.addElement("adList");
	    
		for (Keywords key : list) {

			Set set = key.getKeywordsAdvInfo();
			for (Iterator i = set.iterator(); i.hasNext();) {
				KeywordsAdvInfo ad = (KeywordsAdvInfo) i.next();

				JSONObject json = new JSONObject();
				
				try {
					json.put("title", ad.getTitle());
					json.put("text", ad.getContent());
					json.put("href", ad.getHref());
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				jArr.put(json);
			}

		}
		
		return jArr.toString();
	}
	
	public String getPageAd(String page){
		JSONArray jArr = new JSONArray();
		
		for(int i=0 ;i < 3 ;i++){			
			JSONObject adOffset = new JSONObject();
			
			
			jArr.put(adOffset);
		}
		
		return jArr.toString();
	}
}
